﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin;

[Area("Admin")]
[Authorize]
public class DocreceivedController : Base
{
    private readonly LoginUtil _LoginUtil;
    private readonly ArticleDocreceivedService _articleDocreceivedService;
    private readonly ArticleCateService _articleCateService;
    private readonly ConfigService _configService;
    private readonly AttmentService _attment;
    private readonly LogService _logService;
    private readonly AdminUserService _adminUserService;
    public DocreceivedController(LoginUtil LoginUtil, ArticleDocreceivedService  articleDocreceivedService, ArticleCateService articleCateService,
        LogService logService, AttmentService attmentService, ConfigService configService, AdminUserService adminUserService)
    {
        _LoginUtil = LoginUtil;
        _articleDocreceivedService = articleDocreceivedService;
        _articleCateService = articleCateService;
        _configService = configService;
        _attment = attmentService;
        _logService = logService;
        _adminUserService = adminUserService;
    }

    /// <summary>
    ///  列表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.ArticleDocreceived_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] ArticleDocreceivedQuery query, int limit, int page = 1, int json = 0)
    {
        UserInfo adminUser = await _LoginUtil.UserInfoAsync();

        if (json == 1)
        {

            ArticleDocreceivedQuery articleQuery = new()
            {
                Cid = query.SearchCid ?? query.Cid,
                CurrentPage = page,
                Limit = limit,
                Uid = adminUser.UserId,
                Title = query.Title,
                Miji = query.Miji,
                Clercator = query.Clercator,
                DocNumber = query.DocNumber,
                Uids = await _adminUserService.AdminPostAsUids(adminUser)
            };

            var pagedList = await _articleDocreceivedService.GetListByCidAdminAsync(articleQuery);
            return Json(new { code = 0, count = pagedList.TotalItems, data = pagedList.Items });
        }
        ViewBag.cid = query.Cid;
        ViewBag.catelist = await _articleCateService.CategoryListAsync(adminUser.DeptId, adminUser.Gid, (int)ModelTypeEnum.ModelType.收文管理);
        return View();

    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.ArticleDocreceived_AddOrEdit)]
    public async Task<IActionResult> AddOrEditAsync(int id, int print = 0, int edit = 0, int cid = 0)
    {
        if (edit == 1)
        {
            EditArticleDocreceived data = await _articleDocreceivedService.GetEditAsync(id);
            List<ViewAttment> attments = null;
            if (!string.IsNullOrEmpty(data.Attments))
                attments = await _attment.GetListAsync(data.Attments);
            return Json(new { status = 1, data, attments });
        }
        //附件信息
        SytemConfig configSiteInfo = await _configService.GetByNameAsync();
        ViewBag.fileExts = configSiteInfo.FileExt;
        ViewBag.fileSize = configSiteInfo.FileSize;
        //栏目信息
        ArticleCate articleCate = await _articleCateService.GetInfo(cid);
        ViewBag.cateInfo = articleCate;
        //内容信息
        ViewBag.id = id;
        if (print == 1) return View("Print");
        else return View();
    }

    [HttpPost, ActionName("CreatePost")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.ArticleDocreceived_AddOrEdit)]
    [Log(Name = "新增来文管理")]
    public async Task<IActionResult> CreatePostAsync(EditArticleDocreceived articlePost)
    {
        if (ModelState.IsValid)
        {
            UserInfo adminUser = await _LoginUtil.UserInfoAsync();

            ArticleDocreceived articleRes = new()
            {
                Uid = adminUser.UserId,
                GreatTime = articlePost.GreatTime,
                Department = articlePost.Department,
                Title = articlePost.Title,
                DocNumber = articlePost.DocNumber,
                Clercator = articlePost.Clercator,
                Cid = articlePost.Cid,
                Attments = articlePost.Attments,
                Miji = articlePost.Miji,
                Remarks = articlePost.Remarks,                    
            };

            ArticleDocreceived res = await _articleDocreceivedService.InsertArticleAndContentAsync(articleRes);

            if (res.Id > 0)
            {
                return Json(new { status = 1, msg = "新增来文 Id: " + articleRes.Id, cid = articleRes.Cid });
            }
            else
                return Json(new { status = 0, msg = "新增失败！" });
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { result = 0, msg = error });
        }
    }


    [HttpPost, ActionName("EditPost")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.ArticleDocreceived_AddOrEdit)]
    [Log(Name = "编辑来文管理")]
    public async Task<IActionResult> EditPostAsync(EditArticleDocreceived articlePost)
    {
        if (ModelState.IsValid)
        {
            int x = await _articleDocreceivedService.UpdateArticleAndContentAsync(articlePost);
            if (x > 0)
            {
                return Json(new { status = 1, msg = "修改来文 ID：" + articlePost.Id, cid = articlePost.Cid });
            }
            else
            {
                return Json(new { status = 0, msg = "修改失败！" });
            }
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { status = 0, msg = error });
        }
    }


    [ActionPermissionFilter(Permission = PermissionKeys.ArticleDocreceived_Delete)]
    [Log(Name = "删除来文管理")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _articleDocreceivedService.DelArticleAndContentAsync(id) > 0)
        {
            return Json(new { status = 1, msg = "删除来文 ID：" + id, url = "Docreceived/Index" });
        }
        else
            return Json(new { status = 0, msg = "删除失败！" });
    }
}
